package com.h5lib.server.template;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 *
 * @author farmer
 */
public class TemplateUtil {
 
    private static final Pattern pattern = Pattern.compile("\\%\\%([_A-Za-z0-9]*)\\%\\%");
 
    public static List<TemplateVariable> getVariables(String content) {
    	
        List<TemplateVariable> vars = new ArrayList<TemplateVariable>();
        Matcher m = pattern.matcher(content);
        while (m.find()) {
            TemplateVariable var = new TemplateVariable();
            var.setName(m.group(1));
            String target = m.group(0);
            var.setPattern(target);
            var.setValue(target);
            if (notExist(vars, var.getName())) {
                vars.add(var);
            }
        }
        return vars;
 
    }
 
    public static boolean notExist(List<TemplateVariable> vars, String name) {
 
        for (TemplateVariable var : vars) {
            if (var.getName().equals(name)) {
                return false;
            }
        }
        return true;
    }
 
    public static void setValue(List<TemplateVariable> vars, String name, String value) {
        if (name == null || value == null) {
            return;
        }
        for (TemplateVariable var : vars) {
            if (var.getName().equals(name)) {
                var.setValue(value);
                break;
            }
        }
    }
 
    public static String getResult(List<TemplateVariable> vars, String content) {
        for (TemplateVariable var : vars) {
            if (!var.getPattern().equals(var.getValue()) || var.getValue() != null) {
                content = content.replace(var.getPattern(), var.getValue());
            }
        }
        return content;
    }
 
}